<?php
namespace app\taobao\controller;

use Curl\Curl;
use think\Controller;
use think\Session;
use think\Request;
use app\common\service\User as UserService;
use app\common\model\User as UserModel;


class User extends Controller{
   public function index(){

       return view();
   }

    public function showUserInfo(){
        $userService = new UserService();
        $user = $userService->getCurrentUser();
        //echo $user -> taobaosession;
    }

    public function checkLoginTaobao(){
        $userService = new UserService();
        $user = $userService->getCurrentUser();

        if($user->taobaosession && $user->expire_time > time()){
            $this->success("你已经登录淘宝了",'/admin/index/main');
        }
        return redirect( url('/taobao/user/getCode','','',true));
    }

    /**
     * 第一步
     * @return \think\response\Redirect
     */
    public function getCode(){
         /*
        您在淘宝开放平台成功创建liu526130应用，您的Appkey 和 Appsecret如下：
        App Key： 23870173
        App Secret： 7a216b47de34fbd713879f01aa967706
        接下来您将使用您的APPkey和APPsecret进行应用开发和发布。如果您是第一次开发，建议您详细阅读我们的开发文档，您还可以通过阅读我们的接入指南了解开发流程。

        同时TOP也将不断的完善和推出新的服务，这些信息将会通过论坛公告的形式推送给广大开发者，敬请关注*/
        $taobaoConfig = Config("taobao");
        $url = "https://oauth.taobao.com/authorize?response_type=code&client_id=#appKey#&redirect_uri=http://tb.yangjifang.com&state=1212&view=web";
        $url = str_replace("#appKey#",$taobaoConfig['appKey'],$url);
        return redirect($url);//跳转到这个页面  获取到code 到时候在这页面处理下 跳转到下面的login方法就可以了

    }


    /**
     *curl -i -d "code=OxlukWofLrB1Db1M6aJGF8x2332458&grant_type=authorization_code&client_id=23075594&
    client_secret=69a1469a1469a1469a14a9bf269a14&redirect_uri=http://www.oauth.net/2/ "https://oauth.taobao.com/token
     * @param Request $request
     */
    public function login(Request $request){
        $code = $request->param("code",'','trim');
        if(!$code){
            $this->error("登录淘宝失败",'/admin/index/main');
        }
        $taobaoConfig = Config("taobao");
        $loginUrl = "https://oauth.taobao.com/token?code=#code#&grant_type=authorization_code&client_id=#appKey#&client_secret=#appSecret#&redirect_uri=http://tb.yangjifang.com";
        $loginUrl = str_replace(["#code#","#appKey#","#appSecret#"],[$code,$taobaoConfig["appKey"],$taobaoConfig["appSecret"]],$loginUrl);

        $curl = new Curl();
        $curl->setOpt(CURLOPT_RETURNTRANSFER, TRUE);
        $curl->setOpt(CURLOPT_SSL_VERIFYPEER, FALSE);
        $curl->post($loginUrl);
        $response = $curl->response;
        $response = json_decode($response,true);
        $accessToken = isset($response['access_token'])?$response['access_token']:null;
        if(!$accessToken) exit("登录失败");
        $expireTime = substr(strval($response['expire_time']),0,10);
        $userService = new UserService();
        $userInfo = $userService->getCurrentUser();
        if(!$userInfo){
            $this->error("登录淘宝失败",'/admin/index/main');
        }
        //$userService->update(['id'=>$userInfo['id'],'taobaosession'=>$accessToken]);
        $userModel = UserModel::find($userInfo['id']);
        $userModel->taobaosession = $accessToken;
        $userModel->expire_time = $expireTime;
        $userModel->save();
        $userInfo->taobaosession = $accessToken;
        $userInfo->expire_time = $expireTime;
        $userService -> updateLoginInfo($userInfo);
        $this->success("登录淘宝成功",'/admin/index/main');

        //数据
        /**
         *'taobao_user_nick' => string 'xinlixue20072007' (length=16)
        're_expires_in' => int 3600
        'expires_in' => int 86400
        'expire_time' => float 1501213344783
        'r1_expires_in' => int 86400
        'w2_valid' => float 1501128744783
        'w2_expires_in' => int 1800
        'taobao_user_id' => string '314210378' (length=9)
        'w1_expires_in' => int 86400
        'r1_valid' => float 1501213344783
        'r2_valid' => float 1501213344783
        'w1_valid' => float 1501213344783
        'r2_expires_in' => int 86400
        'token_type' => string 'Bearer' (length=6)
        'refresh_token' => string '6201a229a94d6fa7793e17f06d1f47ZZ93a1df6107e1c44314210378' (length=56)
        'refresh_token_valid_time' => float 1501130544783
        'access_token' => string '620152205f63f8666e3e069544e19ace69e4ccd05f06eda314210378' (length=56)
         */
    }


}